import json
import re
from datetime import datetime


class RatingSystem:



    @staticmethod
    def save(file_name, score, key_word):
        with open(file_name, 'a') as file:
            record = f'keyword:{key_word}\t\tdate:{str(datetime.now())}\t\tscore:{score}\n'
            file.write(record)

    @staticmethod
    def average(file_name):
        total = 0.0
        with open(file_name, 'r') as file:
            lines = file.readlines()
            for line in lines:
                match = re.search(r'score:(\d+\.?\d*)', line)
                total += float(match.group(1))

        average = total / len(lines)
        return average

    @staticmethod
    def scores(T, tp, fp, total=500):
        """

        :param T:   总检出
        :param tp:  检出且认为相关
        :param fp:  未检出且认为相关
        :return:    三个计算准确率的数值
        """
        tn = T - tp
        F = total - T
        fn = F - fp
        N = tn + fn

        recall = tp / (tp + fn)
        precision = tp / (tp + fp)
        f1 = 2 * recall * precision / (recall + precision)
        return recall, precision, f1
